export function setTitle(title) {
	var mobile = navigator.userAgent.toLowerCase();
	if (/iphone|ipad|ipod/.test(mobile)) {
		document.title = title;
		var iframe = document.createElement("iframe");
		iframe.style.display="none";
		iframe.setAttribute("src", "http://named.cn/page/take/img/icon_phone.png");
		var d = function() {
			setTimeout(function() {
				iframe.removeEventListener('load', d);
				document.body.removeChild(iframe);
			}, 0);
		};
		iframe.addEventListener('load', d);
		document.body.appendChild(iframe);
	}
}

export function forceReload(url='') {
			var date_obj = new Date();
			var params = [];
			params['timestamp'] = date_obj.getTime();
			document.querySelector('.forceReloads').innerHTML = date_obj.getTime()+'<br>'+JSON.stringify(params);
			var location_url = url ||  window.location.href;

			var origin = location_url.split('?')[0];
			var query = location.search;

			if (query.indexOf("?") != -1) {
					var param = query.substr(query.indexOf("?")+1);
					param = param.split("&");
					for (var i = 0; i < param.length; i++) {
						let key = unescape(param[i].split("=")[0]);
						if(key == 'timestamp') {
							var value =  date_obj.getTime();
						} else {
							var value =  unescape(param[i].split("=")[1])
						}
						params[key] = value;
					}
			}
			var query_arr = [];
			for(var i in params){
					query_arr.push(i+'='+params[i]);
			}
			if(query_arr){
					if(origin.indexOf('?') > 0) {
						origin += '&' + query_arr.join('&');
					} else {
						origin += '?' + query_arr.join('&');
					}
			}
			window.location.href = origin;
}


/**
 * 图片压缩，默认同比例压缩
 * @param {Object} path
 *   pc端传入的路径可以为相对路径，但是在移动端上必须传入的路径是照相图片储存的绝对路径
 * @param {Object} obj
 *   obj 对象 有 width， height， quality(0-1)
 * @param {Object} callback
 *   回调函数有一个参数，base64的字符串数据
 */
export function dealImage(path, obj, callback){
 var img = new Image();
 img.src = path;
 img.onload = function(){
  var that = this;
  // 默认按比例压缩
  var w = that.width,
   h = that.height,
   scale = w / h;
   w = obj.width || w;
   h = obj.height || (w / scale);
  var quality = 0.5;  // 默认图片质量为0.5
  //生成canvas
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  // 创建属性节点
  var anw = document.createAttribute("width");
  anw.nodeValue = w;
  var anh = document.createAttribute("height");
  anh.nodeValue = h;
  canvas.setAttributeNode(anw);
  canvas.setAttributeNode(anh);
  ctx.drawImage(that, 0, 0, w, h);
  // 图像质量
  if(obj.quality && obj.quality <= 1 && obj.quality > 0){
   quality = obj.quality;
  }
  // quality值越小，所绘制出的图像越模糊
  var urlData = canvas.toDataURL('image/jpeg', quality );
  // 回调函数返回base64的值
	var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte

	//处理异常,将ascii码小于0的转换为大于0
	var ab = new ArrayBuffer(bytes.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < bytes.length; i++) {
			ia[i] = bytes.charCodeAt(i);
	}
	callback(new Blob( [ab] , {type : 'image/png'}))
 }
}


//将图片以二进制流
export function readerImage(file,callback,option={width:null,height:null,quality:0.5})
{
	var reg=/image\/\w+/;
	if(!reg.test(file.type)){	//判断是否为图片
		return false;
	}
	if(file){
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function ( event ) {
			return dealImage(this.result,option,callback);
		}
	}
}

//将图片以二进制流
export function readerAutoImage(file,callback)
{
	var reg=/image\/\w+/;
	if(!reg.test(file.type)){	//判断是否为图片
		return false;
	}
	var size = file.size / 1024;
	var option = {width:750,height:422,quality:2};
	// if(size > 500 && size<1000) {
	// 	option.quality = 1;
	// } else if(size<1500) {
	// 	option.quality = 1;
	// } else if (size<2000) {
	// 	option.quality = 1;
	// } else {
	// 	option.quality = 1;
	// }
	if(file){
		var reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = function ( event ) {
			return dealImage(this.result,option,callback);
		}
	}
}

export function trim(str) {
     return str.replace(/(^\s*)|(\s*$)/g,'');
}

// formate 'YYYY-m-d H:i:s w'
export function getFormateDate(formate,timestamp=(new Date).valueOf()) {
	let dateObject = new Date(timestamp);
	let year = dateObject.getFullYear();
	let month = ('0'+(dateObject.getMonth()+1)).substr(-2);
	let date = ('0'+dateObject.getDate()).substr(-2);
	let hour = ('0'+dateObject.getHours()).substr(-2);
	let minute = ('0'+dateObject.getMinutes()).substr(-2);
	let second = ('0'+dateObject.getSeconds()).substr(-2);
	let week = (function(day){
		var dayName;
		switch (day) {
			case 0:
				dayName = '日';
				break;
			case 1:
					dayName = '一';
					break;
			case 2:
					dayName = '二';
					break;
			case 3:
					dayName = '三';
					break;
			case 4:
					dayName = '四';
					break;
			case 5:
					dayName = '五';
					break;
			case 6:
					dayName = '六';
					break;
			default:
		}
		return dayName;
	})(dateObject.getDay())
	let res = formate;
	res = res.replace('YYYY',year);
	res = res.replace('m',month);
	res = res.replace('d',date);
	res = res.replace('H',hour);
	res = res.replace('i',minute);
	res = res.replace('s',second);
	res = res.replace('w',week);
	return res;
}
